// 模拟出行记录数据存储
const trips = [
  {
    id: 1,
    userId: 1,
    type: '骑行',
    distance: 5.2,
    points: 52,
    dateTime: '2023-06-15 08:30:00',
    carbonReduction: 1.2
  },
  {
    id: 2,
    userId: 1,
    type: '步行',
    distance: 2.1,
    points: 21,
    dateTime: '2023-06-15 12:15:00',
    carbonReduction: 0.3
  }
];

// 添加出行记录
const addTrip = (req, res) => {
  try {
    const { userId, type, distance } = req.body;
    
    // 验证参数
    if (!userId || !type || !distance) {
      return res.status(400).json({
        message: '用户ID、出行类型和距离不能为空',
        code: 400
      });
    }
    
    // 验证出行类型
    const validTypes = ['步行', '骑行', '公交', '地铁'];
    if (!validTypes.includes(type)) {
      return res.status(400).json({
        message: '出行类型不正确',
        code: 400
      });
    }
    
    // 计算积分（简单按距离计算）
    const points = Math.round(distance * 10);
    
    // 计算碳减排量（单位：kg）
    const carbonReduction = distance * 0.2;
    
    // 创建出行记录
    const trip = {
      id: trips.length + 1,
      userId,
      type,
      distance,
      points,
      dateTime: new Date().toISOString().replace('T', ' ').substring(0, 19),
      carbonReduction
    };
    
    trips.push(trip);
    
    res.status(201).json({
      message: '出行记录添加成功',
      code: 201,
      data: {
        trip
      }
    });
  } catch (error) {
    console.error('添加出行记录错误:', error);
    res.status(500).json({
      message: '服务器内部错误',
      code: 500
    });
  }
};

// 获取用户出行记录
const getUserTrips = (req, res) => {
  try {
    const { userId } = req.params;
    
    // 查找用户出行记录
    const userTrips = trips.filter(t => t.userId == userId);
    
    res.json({
      message: '获取出行记录成功',
      code: 200,
      data: {
        trips: userTrips
      }
    });
  } catch (error) {
    console.error('获取出行记录错误:', error);
    res.status(500).json({
      message: '服务器内部错误',
      code: 500
    });
  }
};

module.exports = {
  addTrip,
  getUserTrips
};